// 物体检测系统前端JavaScript

class ObjectDetectionApp {
    constructor() {
        this.isConnected = false;
        this.stats = {
            totalFrames: 0,
            objectCount: 0,
            fps: 0,
            avgInferenceTime: 0,
            cameraFps: 0,
            resolution: ''
        };
        
        this.init();
    }

    init() {
        this.initElements();
        this.bindEvents();
        this.startStatsUpdate();
        this.checkConnection();
    }

    initElements() {
        // 状态显示元素
        this.statusDot = document.getElementById('statusDot');
        this.statusText = document.getElementById('statusText');
        this.videoStream = document.getElementById('videoStream');
        this.videoOverlay = document.getElementById('videoOverlay');
        
        // 统计显示元素
        this.fpsDisplay = document.getElementById('fpsDisplay');
        this.objectCountDisplay = document.getElementById('objectCountDisplay');
        this.totalFramesDisplay = document.getElementById('totalFrames');
        this.avgInferenceTimeDisplay = document.getElementById('avgInferenceTime');
        this.cameraFpsDisplay = document.getElementById('cameraFps');
        this.resolutionDisplay = document.getElementById('resolution');
        
        // 控制元素
        this.detectionToggle = document.getElementById('detectionToggle');
        this.centerToggle = document.getElementById('centerToggle');
        this.statsToggle = document.getElementById('statsToggle');
        this.confidenceSlider = document.getElementById('confidenceSlider');
        this.confidenceValue = document.getElementById('confidenceValue');
        
        // 系统信息元素
        this.systemStatus = document.getElementById('systemStatus');
        this.modelInfo = document.getElementById('modelInfo');
        this.cameraInfo = document.getElementById('cameraInfo');
    }

    bindEvents() {
        // 视频流加载事件
        this.videoStream.onload = () => {
            this.videoOverlay.classList.add('hidden');
            this.updateConnectionStatus(true);
        };

        this.videoStream.onerror = () => {
            this.videoOverlay.classList.remove('hidden');
            this.updateConnectionStatus(false);
        };

        // 控制开关事件
        this.detectionToggle.addEventListener('change', (e) => {
            this.updateSetting('show_detection_boxes', e.target.checked);
        });

        this.centerToggle.addEventListener('change', (e) => {
            this.updateSetting('show_center_point', e.target.checked);
        });

        this.statsToggle.addEventListener('change', (e) => {
            this.updateSetting('show_stats', e.target.checked);
        });

        // 滑块事件
        this.confidenceSlider.addEventListener('input', (e) => {
            const value = parseFloat(e.target.value);
            this.confidenceValue.textContent = value.toFixed(2);
            this.updateSetting('confidence_threshold', value);
        });

        // 页面可见性变化事件
        document.addEventListener('visibilitychange', () => {
            if (document.visibilityState === 'visible') {
                this.checkConnection();
            }
        });
    }

    updateConnectionStatus(connected) {
        this.isConnected = connected;
        
        if (connected) {
            this.statusDot.classList.add('connected');
            this.statusText.textContent = '已连接';
            this.systemStatus.textContent = '正常';
        } else {
            this.statusDot.classList.remove('connected');
            this.statusText.textContent = '连接中...';
            this.systemStatus.textContent = '连接中';
        }
    }

    async updateSetting(key, value) {
        try {
            const response = await fetch('/api/settings', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ [key]: value })
            });

            if (!response.ok) {
                console.error('设置更新失败:', response.statusText);
            }
        } catch (error) {
            console.error('设置更新异常:', error);
        }
    }

    async fetchStats() {
        try {
            const response = await fetch('/api/stats');
            if (response.ok) {
                const data = await response.json();
                this.updateStats(data);
            }
        } catch (error) {
            console.error('获取统计信息失败:', error);
        }
    }

    async fetchSystemInfo() {
        try {
            const response = await fetch('/api/info');
            if (response.ok) {
                const data = await response.json();
                this.updateSystemInfo(data);
            }
        } catch (error) {
            console.error('获取系统信息失败:', error);
        }
    }

    updateStats(data) {
        // 更新统计信息
        if (data.detection_stats) {
            this.fpsDisplay.textContent = (data.detection_stats.fps || 0).toFixed(1);
            this.objectCountDisplay.textContent = data.detection_stats.object_count || 0;
            this.totalFramesDisplay.textContent = data.detection_stats.total_frames || 0;
            
            const avgTime = data.detection_stats.avg_inference_time || 0;
            this.avgInferenceTimeDisplay.textContent = `${(avgTime * 1000).toFixed(1)}ms`;
        }

        if (data.camera_stats) {
            this.cameraFpsDisplay.textContent = (data.camera_stats.fps_actual || 0).toFixed(1);
            
            if (data.camera_info) {
                const { width, height } = data.camera_info;
                this.resolutionDisplay.textContent = `${width}×${height}`;
            }
        }
    }

    updateSystemInfo(data) {
        if (data.model) {
            this.modelInfo.textContent = data.model.name || 'YOLO11';
        }

        if (data.camera) {
            this.cameraInfo.textContent = `设备${data.camera.device_id || 0}`;
        }
    }

    async checkConnection() {
        try {
            const response = await fetch('/api/health');
            this.updateConnectionStatus(response.ok);
        } catch (error) {
            this.updateConnectionStatus(false);
        }
    }

    startStatsUpdate() {
        // 定期更新统计信息
        setInterval(() => {
            if (this.isConnected) {
                this.fetchStats();
            }
        }, 1000);

        // 定期更新系统信息
        setInterval(() => {
            if (this.isConnected) {
                this.fetchSystemInfo();
            }
        }, 5000);

        // 定期检查连接
        setInterval(() => {
            this.checkConnection();
        }, 10000);
    }
}

// 全局函数
function resetSettings() {
    // 重置所有设置到默认值
    document.getElementById('detectionToggle').checked = true;
    document.getElementById('centerToggle').checked = true;
    document.getElementById('statsToggle').checked = true;
    document.getElementById('confidenceSlider').value = 0.6;
    document.getElementById('confidenceValue').textContent = '0.60';
    
    // 发送重置请求
    fetch('/api/settings/reset', { method: 'POST' })
        .then(response => {
            if (response.ok) {
                console.log('设置已重置');
            }
        })
        .catch(error => {
            console.error('重置设置失败:', error);
        });
}

// 删除刷新页面和全屏功能
// function refreshPage() {
//     window.location.reload();
// }

// function toggleFullscreen() {
//     if (!document.fullscreenElement) {
//         document.documentElement.requestFullscreen().catch(err => {
//             console.log('进入全屏失败:', err);
//         });
//     } else {
//         document.exitFullscreen();
//     }
// }

// 初始化应用
document.addEventListener('DOMContentLoaded', () => {
    window.objectDetectionApp = new ObjectDetectionApp();
});